from typing import List
from database.database import Database
from model.dbmodel import DbParkToken
from datetime import datetime


class ParkTokenTable(Database):
    def __init__(self):
        self.table_name = "park_tokens"

    def insert(self, info: DbParkToken, commit=False):
        sql = self.get_insert_sql_from_obj(info, self.table_name)
        self.execute(sql)
        if commit:
            self.commit()
        return int(self.cursor.lastrowid)

    def query(self, id: int) -> DbParkToken:
        sql = f"select * from {self.table_name} where `id` = {id}"
        self.execute(sql)
        result = self.cursor.fetchone()
        if not result:
            return None
        return DbParkToken().load(result)
    
    def query_all(self, platform_id: int, second: int = -1) -> List[DbParkToken]:
        sql = f"select * from {self.table_name} where `platform_id` = {platform_id}"
        if second > 0:
            sql += f" and `gmt_modified` > DATE_SUB(NOW(), INTERVAL {second} SECOND)"
        self.execute(sql)
        tokens = [DbParkToken().load(record) for record in self.cursor.fetchall()]
        return tokens
    
    def find(self, user: str, platform_id: int) -> DbParkToken:
        sql = f"select * from {self.table_name} where `user` = '{user}' and `platform_id` = {platform_id}"
        self.execute(sql)
        result = self.cursor.fetchone()
        if not result:
            return None
        return DbParkToken().load(result)
